<!--
 * @Author: wangshuixin 2412658453@qq.com
 * @Date: 2024-11-26 13:36:51
 * @LastEditors: wangshuixin 2412658453@qq.com
 * @LastEditTime: 2025-01-21 10:50:25
 * @FilePath: \sr_system_manager_ui\src\views\resultsManagement\components\ResearchAward\index.vue
 * @Description: 成果管理 - 科研获奖管理 - 列表
-->
<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ResultAttachmentModal from '../ResultAttachmentModal.vue'
import { StatusColorMap, StatusMap } from '@/utils/constText'
import { downloadFile } from '@/utils/download'
import useUserStore from '@/store/modules/user'
import { deleteResultsManagementApi, approveResultsManagementApi, getAllDepartmentListApi, approvalBatchApi } from '@/api/resultsManagement/index'
import { getResearchAwardListApi, exportResearchAwardApi } from '@/api/resultsManagement/researchAwardApi'
import type { SelectComponentDataDTO } from '@/types/component'
import type { PaginationQueryUniteRespDTO, AppStateChangeRespDTO, AttachmentFileInfoDTO } from '@/types/index'
import type { ResearchAwardListResp } from '@/types/resultsManagement'

const props = defineProps({
  /* 模块类型：college 学院成果管理；office 科研处成果管理；mine 我的成果； */
  moduleType: {
    type: String as PropType<'college' | 'office' | 'mine'>,
    default: 'college',
  },
})
const route = useRoute()
const status = computed(() => {
	return Number(route.query.status) || undefined
})
const hasRejectPermi = computed(() => useUserStore().permissions?.includes('achievementReward:office:office-research-award:reject'))
// 学院、部门列表
const departmentArray = ref<SelectComponentDataDTO[]>([])
const showAttachmentModal = ref(false)  //  附件弹框
// 附件预览
const attachmentFileList = ref<{ title: string, files?: AttachmentFileInfoDTO[] }[]>([])   //  选中行附件

// 搜索条件组件配置数据
const conditionComponents = computed(() => {
  const arr0 = [
    {
      type: 1,
      key: 'departmentId',
      placeholder: '请选择学院（部）',
      config: {
        options: departmentArray.value
      }
    }
  ]
  const arr1 = [{
    type: 0,
    key: 'codeOrName',
    placeholder: '请输入工号/姓名',
  },
  {
    type: 0,
    key: 'name',
    placeholder: '请输入项目名称',
  },
  {
    type: 0,
    key: 'projectType',
    placeholder: '请输入类别',
  },
  {
    type: 2,
    key: 'businessDateArray',
    width: '456px',
    config: {
      startPlaceholder: '请选择获奖日期开始时间',
      endPlaceholder: '请选择获奖日期结束时间',
    }
  },
  {
    type: 0,
    key: 'approvedBy',
    placeholder: '批准单位',
  },
  {
    type: 1,
    key: 'researchScoreFlag',
    placeholder: '请选择科研分认定范畴',
    config: {
      options: [
        {title: '属于科研分认定范畴', value: true},
        {title: '不属于科研分认定范畴', value: false},
      ]
    }
  },
  {
    type: 1,
    key: 'outcomeFlag',
    placeholder: '请选择项目成果类型',
    config: {
      options: [
        {title: '属于项目成果', value: true},
        {title: '不属于项目成果', value: false},
      ]
    }
  },
  {
    type: 2,
    key: 'statisticalYearArray',
    width: '456px',
    config: {
      startPlaceholder: '请选择统计年度日开始时间',
      endPlaceholder: '请选择统计年度结束时间',
      type: 'yearrange',
      valueFormat: 'YYYY'
    }
  },
  {
    type: 1,
    key: 'status',
    cValue: status.value,
    placeholder: '请选择状态',
    config: {
      options: [
        {title: '待学院（部）审核', value: 1},
        {title: '待科研处审核', value: 2},
        {title: '学院审核不通过', value: 3},
        {title: '科研处审核不通过', value: 4},
        {title: '已登记', value: 5},
      ]
    }
  }]
  const arr2 = [{
    type: 0,
    key: 'name',
    placeholder: '请输入项目名称',
  }, {
    type: 1,
    key: 'status',
    placeholder: '请选择状态',
    config: {
      options: [
        {title: '待提交', value: 0},
        {title: '待学院（部）审核', value: 1},
        {title: '待科研处审核', value: 2},
        {title: '学院审核不通过', value: 3},
        {title: '科研处审核不通过', value: 4},
        {title: '已登记', value: 5},
      ]
    }
  }]
  return props.moduleType === 'mine' ? arr2 : (props.moduleType === 'office' ? [...arr0, ...arr1] : arr1)
})

// 表头
const columns = computed(() => {
  const arr1 = [
    {
      title: '序号',
      width: 46,
      dataIndex: 'index',
      slotName: 'index',
    }
  ]
  const arr2 = [
    {
      title: '学院（部）',
      minWidth: 60,
      dataIndex: 'departmentName',
      slotName: 'departmentName',
    },
    {
      title: '工号',
      minWidth: 40,
      dataIndex: 'accountCode',
      slotName: 'accountCode',
    },
    {
      title: '姓名',
      minWidth: 40,
      dataIndex: 'accountName',
      slotName: 'accountName',
    }
  ]
  const arr3 = [
    {
      title: '项目名称',
      minWidth: 200,
      dataIndex: 'name',
      slotName: 'name',
    },
    {
      title: '类别',
      minWidth: 40,
      dataIndex: 'projectType',
      slotName: 'projectType',
    },
    {
      title: '认定等级',
      minWidth: 50,
      dataIndex: 'recognitionLevelName',
      slotName: 'recognitionLevelName',
    },
    {
      title: '批准单位',
      minWidth: 80,
      dataIndex: 'approvedBy',
      slotName: 'approvedBy',
    },
    {
      title: '获奖日期',
      minWidth: 60,
      dataIndex: 'businessDate',
      slotName: 'businessDate',
    },
    {
      title: '科研分',
      minWidth: 40,
      dataIndex: 'researchScore',
      slotName: 'researchScore',
    },
    {
      title: '统计年度',
      minWidth: 54,
      dataIndex: 'statisticalYear',
      slotName: 'statisticalYear',
    }
  ]
  const arr4 = [
    {
      title: '附件',
      minWidth: 50,
      dataIndex: 'attachment',
      slotName: 'attachment',
    }
  ]
  const arr5 = [
    {
      title: '状态',
      minWidth: 54,
      dataIndex: 'status',
      slotName: 'status',
    },
    {
      title: '操作',
      minWidth: computed(() => { return props.moduleType === 'mine' ? 110 : 100 }),
      dataIndex: 'option',
      slotName: 'option',
    }
  ]
  return props.moduleType === 'mine' ? [...arr1, ...arr3, ...arr5] : [...arr1, ...arr2, ...arr3, ...arr4, ...arr5]
})

const router = useRouter();

// 条件搜索引用
const searchBarRef = ref()
// 表格列表引用
const tableFormRef = ref()
// 用户信息
const userStore = useUserStore()
// 列表数据
const dataList = ref<ResearchAwardListResp[]>([])
// 数据总条数
const total = ref(0)
// 展示搜索条件组件框
const showSearch = ref(true)
// 当前选中数据
const currentRowData = ref()
// 显示提交弹框
const showSubmitSave = ref(false)
// 显示审核弹框
const showApproveAlert = ref(false)
// 显示打回弹框
const showRepulseAlert = ref(false)
// 显示 审核记录 弹框
const showCheckRecordAlert = ref(false)
// 显示删除弹框
const showDeleteAlert = ref(false)
// 显示 批量审核 弹框
const showApproveBatchAlert = ref(false)
// 表格loading
const tableLoading = computed(() => { return loading.value || deleteLoading.value })
// 请求参数
const parameters = ref({
  page: 1,
  size: 20,
  unStatus: computed(() => { return props.moduleType !== 'mine' ? 0 : undefined }),
  createdBy: computed(() => { return props.moduleType === 'mine' ? userStore.id : undefined }),
  departmentId: computed(() => { return props.moduleType === 'college' ? userStore.departmentId : undefined }), // 学院（部）
  codeOrName: undefined, // 工号/姓名
  name: undefined, // 专利/软著名称
  patentNumber: undefined, // 专利号/登记号
  businessDateArray: undefined,
  businessStartDate: undefined, // 授权公告日开始时间
  businessEndDate: undefined, // 授权公告日结束时间
  patentType: undefined, // 专利/软著类别
  outcomeFlag: undefined, // 项目成果类型
  researchScoreFlag: undefined, // 是否属于科研分认定范畴
  statisticalYearArray: undefined,
  statisticalStartYear: undefined, // 统计年度日开始时间
  statisticalEndYear: undefined, // 统计年度结束时间
  status: status.value, // 流程状态
})
// 导出参数
const downloadParameters = ref({
  unStatus: computed(() => { return props.moduleType !== 'mine' ? 0 : undefined }),
  createdBy: computed(() => { return props.moduleType === 'mine' ? userStore.id : undefined }),
  departmentId: computed(() => { return props.moduleType === 'college' ? userStore.departmentId : undefined }), // 学院（部
  idList: []
})

/* 查询专利软著列表 */
const { run: getDataList, loading } = useRequest(getResearchAwardListApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: PaginationQueryUniteRespDTO<ResearchAwardListResp>) => {
    if (response.content) {
      dataList.value = response.content
    }else{
      dataList.value = []
    }
    total.value = response.totalElements || 0;
  },
  // 请求失败
  onError: () => {
  },
})

/* 删除专利软著 */
const { run: deleteResearchAward, loading: deleteLoading } = useRequest(deleteResultsManagementApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO, params) => {
    if (response.isSuccess) {
      if (params[0].status === 1) {
        ElMessage.success('提交成功')
      } else if (params[0].status === 2 || params[0].status === 5) {
        ElMessage.success('审核通过')
      } else if (params[0].status === 3 || params[0].status === 4) {
        ElMessage.success('审核不通过')
      }
      getDataList(parameters.value)
    }
  },
  // 请求失败
  onError: () => {
  },
})

/* 审核 */
const { run: approveDetail, loading: approveLoading } = useRequest(approveResultsManagementApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO, params) => {
    if (response.isSuccess) {
      if (params[0].status === 1) {
        ElMessage.success('提交成功')
      } else if (params[0].status === 2 || params[0].status === 5) {
        ElMessage.success('审核通过')
      } else if (params[0].status === 3 || params[0].status === 4) {
        ElMessage.success('审核不通过')
      } else if (params[0].status === 0) {
        ElMessage.success('打回成功')
      }
      refreshTableData(searchBarRef.value.params)
    }
  },
  // 请求失败
  onError: () => {
  },
})

/* 学院、部门列表 */
const { run: getAllDepartmentList, loading: departmentListLoading } = useRequest(getAllDepartmentListApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: any[]) => {
    if (response) {
      departmentArray.value = response.map(department => {
        return {
          ...department,
          title: department.departmentName,
          value: department.departmentId
        }
      })
    } else {
      departmentArray.value = []
    }
  },
  // 请求失败
  onError: () => {
  },
})

/* 批量审核 */
const { run: approvalBatch, loading: approvalBatchLoading } = useRequest(approvalBatchApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO, params) => {
    if (response.isSuccess) {
      if (params[0].status === 2 || params[0].status === 5) {
        ElMessage.success('审核通过')
      } else if (params[0].status === 3 || params[0].status === 4) {
        ElMessage.success('审核不通过')
      }
      refreshTableData(searchBarRef.value.params)
    }
  },
  // 请求失败
  onError: () => {
  },
})

// 刷新列表
function refreshTableData(params) {
  parameters.value = {...parameters.value, ...params}
  parameters.value = {
    ...parameters.value,
    businessStartDate: (parameters.value.businessDateArray ? parameters.value.businessDateArray[0] : undefined),
    businessEndDate: (parameters.value.businessDateArray ? parameters.value.businessDateArray[1] : undefined),
    statisticalStartYear: (parameters.value.statisticalYearArray ? parameters.value.statisticalYearArray[0] : undefined),
    statisticalEndYear: (parameters.value.statisticalYearArray ? parameters.value.statisticalYearArray[1] : undefined),
  }
  getDataList(parameters.value)
}

/* 导出列表数据 */
const { runAsync: exportFile } = useRequest(exportResearchAwardApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: () => {
  },
  // 请求失败
  onError: () => {
  },
})
// 导出
const exportListData = async (params) => {
  downloadParameters.value.idList = params
  const res = await exportFile({
    ...downloadParameters.value,
    ...searchBarRef.value.params,
    businessStartDate: (parameters.value.businessDateArray ? parameters.value.businessDateArray[0] : undefined),
    businessEndDate: (parameters.value.businessDateArray ? parameters.value.businessDateArray[1] : undefined),
    statisticalStartYear: (parameters.value.statisticalYearArray ? parameters.value.statisticalYearArray[0] : undefined),
    statisticalEndYear: (parameters.value.statisticalYearArray ? parameters.value.statisticalYearArray[1] : undefined),
  })
  downloadFile(res)
}

// 新增
const addEvent = () => {
  if (props.moduleType === 'mine') {
    router.push({
      name: 'mine-research-award-detail',
      query: {}
    })
  } else {
    if (tableFormRef.value.selectedRowKeys && tableFormRef.value.selectedRowKeys.length > 0) {
      showApproveBatchAlert.value = true
    } else {
      ElMessage.warning('请先勾选数据！')
    }
  }
}

// 批量审核 通过
const approveBatchEvent = (params: any) => {
  showApproveBatchAlert.value = false
  approvalBatch({ids: tableFormRef.value.selectedRowKeys, status: props.moduleType === 'college' ? 2 : 5, description: params.auditMessage, fileIds: [] })
}
// 批量审核 不通过
const disApproveBatchEvent = (params: any) => {
  showApproveBatchAlert.value = false
  approvalBatch({ids: tableFormRef.value.selectedRowKeys, status: props.moduleType === 'college' ? 3 : 4, description: params.auditMessage, fileIds: [] })
}
// 详情
const detailEvent = (record: any) => {
  router.push({
    name: (props.moduleType === 'college' ? 'college-research-award-detail' : (props.moduleType === 'office' ? 'office-research-award-detail' : 'mine-research-award-detail')),
    query: { id: record.id, mode: 'preview' }
  })
}
// 审核弹框
const approveAlertEvent = (record: any) => {
  currentRowData.value = record
  showApproveAlert.value = true
}
// 审核通过
const approveEvent = (record: any, params: any) => {
  showApproveAlert.value = false
  approveDetail({ id: record.id as string, status: props.moduleType === 'college' ? 2 : 5, description: params.auditMessage, fileIds: [] })
}
// 审核不通过
const disApproveEvent = (record: any, params: any) => {
  showApproveAlert.value = false
  approveDetail({ id: record.id as string, status: props.moduleType === 'college' ? 3 : 4, description: params.auditMessage, fileIds: [] })
}
// 提交弹框
const submitAlertEvent = (record: any) => {
  currentRowData.value = record
  showSubmitSave.value = true
}
// 提交
const submitForm = (record: any) => {  
  if (props.moduleType === 'mine') {
    showSubmitSave.value = false
    approveDetail({ id: record.id as string, status: 1 })
  }
}
// 打回弹框
const RepulseAlertEvent = (record: any) => {
  currentRowData.value = record
  showRepulseAlert.value = true
}
// 打回
const RepulseEvent = (record: any, params: any) => {
  showRepulseAlert.value = false
  approveDetail({ id: record.id as string, status: 0, description: params.repulseMessage, fileIds: [] })
}
// 审核记录弹框
const checkRecordAlertEvent = (record: any) => {
  currentRowData.value = record
  showCheckRecordAlert.value = true
}
// 编辑
const editEvent = (record: any) => {
  router.push({
    name: (props.moduleType === 'college' ? 'college-research-award-detail' : (props.moduleType === 'office' ? 'office-research-award-detail' : 'mine-research-award-detail')),
    query: { id: record.id, mode: 'edit' }
  })
}
// 删除弹框
const deleteAlertEvent = (record: any) => {
  currentRowData.value = record
  showDeleteAlert.value = true
}
// 删除数据行
const deleteEvent = (record: any) => {
  showDeleteAlert.value = false
  deleteResearchAward({ id: record.id })
}

// 查看附件
const previewFile = (record: any) => {
  const attachments = [
    {
      title: '获奖证书及相关材料',
      files: record?.awardCertificateFileList,
    },
    {
      title: '红头文件',
      files:  record?.redFileList,
    },
    {
      title: '其他附件',
      files: record?.fileList
    }
  ]
  attachmentFileList.value = attachments
  showAttachmentModal.value = true
}

onMounted(() => {
  getAllDepartmentList()
  refreshTableData(searchBarRef.value.params)
})

</script>

<template>
  <div>
    <div v-if="showSearch" style="padding: 16px 20px;margin-bottom: 16px;border-radius: 4px;background-color: white;">
      <x-search-bar
        ref="searchBarRef"
        :components="conditionComponents"
        :hideRightArea="false"
        @search="refreshTableData"
      />
    </div>
    <div style="padding: 16px 20px;padding-top: 0px;background-color: white;">
      <x-table-form
        ref="tableFormRef"
        :data="dataList"
        :columns="columns"
        :tableLoading="tableLoading"
        :total-count="total"
        v-model:showSearch="showSearch"
        :showRowSelection="true"
        :show-tool-bar="true"
        :hideLeftMenu="false"
        :autoHeight="true"
        :btn-title="`${ props.moduleType === 'mine' ? '新增' : '批量审核'}`"
        :right-first-btn-permission="['mine:mine-research-award:export', 'achievementReward:college:college-research-award:export', 'achievementReward:office:office-research-award:export']"
        :left-menu-permission="['mine:mine-research-award:add', 'achievementReward:college:college-research-award:batchAudit', 'achievementReward:office:office-research-award:batchAudit']"
        @btn-click="addEvent"
        :download="(params) => { exportListData(params)}"
        @refresh="refreshTableData"
      >
        <template #index="{rowIndex}">
          {{ rowIndex + 1 }}
        </template>
        <template #status="{record}">
          <div class="status-box">
            <div
              class="status-dot"
              :style="`background-color: ${StatusColorMap[record.status as keyof typeof StatusColorMap]}`"
            />
            <div class="status-text" :style="`color: ${StatusColorMap[record.status as keyof typeof StatusColorMap]}`">{{ StatusMap[record.status as keyof typeof StatusMap] }}</div>
          </div>
        </template>
        <template #researchScore="{record}">
          <span v-if="record.researchScoreFlag">
            {{ record.researchScore }}
          </span>
          <span v-else>-</span>
        </template>
        <template #attachment="{ record }">
          <a class="btn-text" @click="previewFile(record)" @dblclick.stop>点击查看</a>
        </template>
        <template #option="{record}">
          <div class="optionClass">
            <el-button v-if="props.moduleType === 'mine' && record.status === 0" v-hasPermi="['mine:mine-research-award:submit']" link type="primary" @click="submitAlertEvent(record)" @dblclick.stop>提交</el-button>
            <el-button link type="primary" v-hasPermi="['mine:mine-research-award:detail', 'achievementReward:college:college-research-award:detail', 'achievementReward:office:office-research-award:detail']" @click="detailEvent(record)">详情</el-button>
            <el-button v-if="(props.moduleType === 'college' && record.status === 1) || (props.moduleType === 'office' && record.status === 2)" v-hasPermi="['achievementReward:college:college-research-award:audit', 'achievementReward:office:office-research-award:audit']" link type="primary" @click="approveAlertEvent(record)" @dblclick.stop>审核</el-button>
            <el-button v-if="props.moduleType === 'office' && hasRejectPermi" link type="danger" @click="RepulseAlertEvent(record)">打回</el-button>
            <el-button v-if="props.moduleType === 'college' || props.moduleType === 'office'" v-hasPermi="['achievementReward:college:college-research-award:auditRecord', 'achievementReward:office:office-research-award:auditRecord']" link type="primary" @click="checkRecordAlertEvent(record)" @dblclick.stop>审核记录</el-button>
            <el-button v-if="props.moduleType === 'mine' && (record.status === 0 || record.status === 3 || record.status === 4)" v-hasPermi="['mine:mine-research-award:edit']" link type="primary" @click="editEvent(record)" @dblclick.stop>编辑</el-button>
            <el-button v-if="props.moduleType === 'mine' && (record.status === 0 || record.status === 3 || record.status === 4)" v-hasPermi="['mine:mine-research-award:del']" link type="danger" @click="deleteAlertEvent(record)"  @dblclick.stop>删除</el-button>
          </div>
        </template>
      </x-table-form>
    </div>
    <DelConfirmModal v-if="showSubmitSave" :visible="showSubmitSave" text="是否确认提交？" ok-text="确定" @cancel="() => { showSubmitSave = false }" @ok="submitForm(currentRowData)" />
    <AuditModal v-if="showApproveAlert" :visible="showApproveAlert" @ok="(params) => { approveEvent(currentRowData, params) }" @cancel="(params) => { disApproveEvent(currentRowData, params) }" @close="showApproveAlert = false"></AuditModal>
    <AuditModal v-if="showApproveBatchAlert" :visible="showApproveBatchAlert" @ok="(params) => { approveBatchEvent(params) }" @cancel="(params) => { disApproveBatchEvent(params) }" @close="showApproveBatchAlert = false"></AuditModal>
    <!-- 审核记录 -->
    <AuditRecordDrawer v-if="showCheckRecordAlert" v-model:visible="showCheckRecordAlert" :project-id="currentRowData.id" />
    <DelConfirmModal v-if="showDeleteAlert" :visible="showDeleteAlert" text="是否确认删除？" ok-text="删除" @cancel="showDeleteAlert = false" @ok="deleteEvent(currentRowData)" />
    <RepulseModal v-if="showRepulseAlert" :visible="showRepulseAlert" @ok="(params) => { RepulseEvent(currentRowData, params) }" @close="showRepulseAlert = false"></RepulseModal>
    <!-- 附件 -->
    <ResultAttachmentModal :file-list="attachmentFileList" v-if="showAttachmentModal" @close="showAttachmentModal = false" :visible="showAttachmentModal"></ResultAttachmentModal>
  </div>
</template>

<style scoped lang="scss">
.optionClass {
  margin-left: -8px;
  :deep(.el-button) {
    margin-left: 8px;
    padding: 0px;
  }
}
.status-box {
  display: flex;
  align-items: center;
  flex-direction: row;
  .status-dot {
    width: 6px;
    height: 6px;
    border-radius: 3px;
    margin-right: 8px;
  }
  .status-text {
    width: calc(100% - 14px);
  }
}
.attachmentBtn {
  cursor: pointer;
  color: #57A9FB;
}
.attachmentBtn:hover {
  color: #3491FA;
}
</style>